/**
 * @file 工单操作列表、操作权限控制
 * @author yangjiangming <449654337@qq.com>
 * @date 2018/12/10 11:17:55
 */

var dependsList = [
    'tooltipster', 'zmnUtils', '$http', '$api',
    'oms_work_config', 'oms_common_table_config'
];

layui.define(dependsList, function (exports) {
    var $ = layui.$;
    var config = layui.oms_work_config;
    var zmnUtils = layui.zmnUtils;
    var $http = layui.$http;
    var $api = layui.$api;
    var workTableConfiger = layui.oms_common_table_config;
    var tooltipster = layui.tooltipster;

    var OPERATE_LIST_URL = config.operateListURL;
    var OPERATE_OBJECT_URL = config.operateObjectURL;

    var operationList = config.operationList;
    var MODULE_ID_YEYX = 590;
    var MODULE_ID_SAAS = 572;
    var MODULE_ID_CNHB = 574;
    var MODULE_ID_ZS = 510;

    try {
        var tableConfig = workTableConfiger.createTableConfig(tableName || "");
    }catch (e) {}

    if(tableConfig){
        moduleId = tableConfig.moduleId;
    }

    function _getOpConfigById (id) {
        return operationList.find((op) => op.id === +id) || {};
    }

    function mapUrl (o) {
        if (Object.prototype.toString.call(o) === '[object Array]') {
            return o.map((op) => {
                op.url = '';
                var operation = findOperationById(op.id);

                if (operation) {
                    op.url = operation.url;
                }

                return op;
            });
        } else if (Object.prototype.toString.call(o) === '[object Object]') {
            var op = findOperationById(o.id);
            if (op.url) {
                o.url = op.url;
                return o;
            }

            return o;
        }

    }

    function _specialOperateHandlerForComplaintAndAbnormal (opConfigObj, params, goFuncForList, goFuncForEdit) {
        if (opConfigObj.id === 502 || opConfigObj.id === 503) {
            var checkFunc = opConfigObj.id === 502 ? $api.permitComplaint : $api.permitAbnormal;
            var text = opConfigObj.id === 502 ? '投诉' : '异常';


            checkFunc(params).done(function (data) {
                if (data > 0) {
                    if (opConfigObj.id === 502){
                        var complaintDetailParams = {
                            complainId: data
                        };
                        layer.confirm('工单有' + text + '正在进行中，是否查看？', {icon: 3, title: '提示'}, function (index) {
                            var url = zmnUtils.serializeURL(opConfigObj.host + opConfigObj.detailURL, complaintDetailParams);
                            openComplaintIframe(text + '详情', url);
                            layer.close(index);
                        });
                    } else {
                        layer.confirm('是否前往查看工单' + text + '？', {icon: 3, title: '提示'}, function (index) {
                            goFuncForList(text + '列表');
                            layer.close(index);
                        });
                    }
                } else {
                    $api.permitCheck({ permit: opConfigObj.id, moduleId: moduleId }).then(function () {
                        if (opConfigObj.id === 502){
                            var queryParams = {
                                workId: params.workId,
                                orderId: params.orderId,
                                sourceType: 9
                            };
                            var url = zmnUtils.serializeURL(opConfigObj.host + opConfigObj.editURL, queryParams);
                            openComplaintIframe('新增' + text, url);
                        } else {
                            layer.confirm('当前工单无' + text + '，是否确认添加？', {icon: 3, title: '提示'}, function (index) {
                                goFuncForEdit('新增' + text);
                                layer.close(index);
                            });
                        }
                    }, function (msg) {
                        layer.msg('当前工单无' + text);
                    });
                }
            });
        }
    }

    // 投诉弹框。
    function openComplaintIframe(text, url){
        layer.open({
            type: 2,
            title: text,
            shade: [0.8, '#393D49'],
            area: ['98%', '96vh'],
            minWidth: '960px',
            content: url
        });
    }

    function findOperationById (id) {
        return operationList.find((operation) => {
            return operation.id === id;
        });
    }

    function getUrlById (id) {
        var operation = findOperationById(id);
        return operation ? operation.url : '';
    }

    function operatePermissionFactory (url) {
        return function (params) {
            return $http.$get(url, params).fail(function () {
                layer.msg('网络错误，请重试');
            });
        }
    }

    var fetchOperationList  = operatePermissionFactory(OPERATE_LIST_URL);
    var fetchOperationObj  = operatePermissionFactory(OPERATE_OBJECT_URL);


    /**
     * 打开对话框
     * @param {Object} config 配置
     */
    function openDialog (config) {
        var defaultConfig = {
            type: 2,
            content: '/',
            title: '',
            shade: [0.8, '#393D49'],
            area: ['98%', '96vh'],
            minWidth: '960px',
            zIndex: layer.zIndex, // 重点1
            success: function(layero) {
                parent.layer.setTop(layero); // 重点2
                var iframeWindow = layero.find('iframe')[0].contentWindow;
                iframeWindow.workList = layui.table.cache['zmn-work-table'];
                iframeWindow.setCurrentWork = function (work) {
                    window.currentWork = work;
                }
            }
        };

        var normalizedConfig = Object.assign({}, defaultConfig, config);
        parent.layer.open(normalizedConfig);
    }


    /**
     * 跳转到页面
     * @param params
     * @param opConfigObj 配置文件
     */
    function jumpToPage(params, opConfigObj) {
        // 初始赋值
        let url =  params.url;

        // 清除多余的请求参数
        delete params.url;

        window.currentWork = params;
        var operateURL = zmnUtils.serializeURL(url, params);
        opConfigObj.callback(params, function (data) {
            openDialog({
                title: opConfigObj.name,
                content: operateURL,
                end: function () {
                    window.updateRowDataByWorkId();
                }
            });
        });

    }

    /**
     * 打开确认对话框
     * @param params 请求参数
     * @param opConfigObj 配置对象
     * @param btnList 按钮列表
     * @param content 内容
     * @param yesCallBack 第一个按钮callback，默认为跳转到派单页面
     * @param btn2CallBack 第二个按钮callback，默认为跳转到改派列表
     */
    function openConfirmDialog(params, opConfigObj, btnList, content, yesCallBack, btn2CallBack) {
        layer.open({
            title: '提示',
            btn: btnList,
            content: content,
            yes: function (index, layero) {

                if (typeof yesCallBack === "function") {
                    yesCallBack();
                } else {
                    // 跳转到派单页面
                    jumpToPage(params, opConfigObj)
                }

                // 关闭对话框
                layer.close(index);
            },
            btn2: function (index, layero) {

                if (typeof btn2CallBack === "function") {
                    btn2CallBack();
                } else {

                    // 跳转到改派列表
                    layer.msg('正在跳转到改派列表。', {time: 1500}, function () {
                        let url = OMS_BASE_URL + "/work/redistribute/list.action";
                        let operateURL = zmnUtils.serializeURL(url, {
                            orderId: params.orderId
                        });
                        top.layui.index.openTabsPage(operateURL, '改派列表');
                        parent.layer.closeAll();
                    });

                }

                // 关闭对话框
                layer.close(index);
            }
        });
    }


    /**
     * 跳转至【派单】或【改派列表】页面
     * @param data 待改派的记录
     * @param params
     * @param opConfigObj
     */
    function jumpToDistributeOrRedistributePage(data, params, opConfigObj) {
        if (data.redistributeId) {

            // 如果【审核状态】不是【待审核或处理中】
            if (!(data.auditStatus == 1 || data.auditStatus == 5)) {
                openConfirmDialog(params, opConfigObj, ['直接改派', '取消'], '正在向附近的工程师发起改派求助，目前还没有工程师领单，确定直接改派订单吗？', null, () => {
                })
                return;
            }

            // 待【工程师主管】或【员工】审核
            switch (data.auditType) {
                case 1: // 主管
                    openConfirmDialog(params, opConfigObj, ['直接改派', '等待主管处理'], '存在需工程师审核的取消申请，确定直接取消订单吗？', null, () => {
                    })
                    break;
                case 2: // 员工
                    openConfirmDialog(params, opConfigObj, ['直接改派', '前去处理'], '存在进行中的改派申请，确定直接改派订单吗？', null, null)
                    break;
                default:
                    layer.msg("未知的审核人类型");
                    break;
            }

        } else {
            // 否则，走原有逻辑
            jumpToPage(params, opConfigObj)
        }
    }




    /**
     * 生成工单操作下拉列表
     * @param {array} data 数据
     * @returns {string} html 字符串
     */
    function createOperationPanelHtml (data) {
        var htmlStr = '<div class="operator-panel">';

        $.each(data, function (index, item) {
            var classArr = ['layui-btn', 'layui-btn-primary', 'layui-btn-sm'];
            if (!item.canOperate) {
                classArr.push('layui-btn-disabled');
            }

            htmlStr += '<button class="' + classArr.join(' ') +
                '" data-url="' + item.url + '" data-id="' + item.id + '">' + item.name +'</button>'

        });

        htmlStr += '</div>';

        return htmlStr;
    }

    /**
     * 绑定操作面板按钮事件
     * @param htmlStr
     * @param params
     * @returns {jQuery}
     */
    function bindEventForOperateButton (htmlStr, params) {
        return $(htmlStr).on('click', 'button', function () {
            var $button = $(this);
            var operateId = $button.data('id');
            var config = $.extend({}, params, { type: operateId });

            fetchOperationObj(config).done(function (operate) {
                if (operate && operate.canOperate) {
                    var opConfigObj = _getOpConfigById(operateId);
                    var url = opConfigObj ? opConfigObj.url : '';

                    // 特殊处理项
                    if (opConfigObj && opConfigObj.special) {
                        if(opConfigObj.callback){
                            if (opConfigObj.id === 9) {
                                window.currentWork = params;
                                opConfigObj.callback(params, function (data) {
                                    layer.msg('算账成功', {
                                        icon: 1,
                                        time: 1000
                                    }, function () {
                                        window.updateRowDataByWorkId();
                                    })
                                });
                            }else if (opConfigObj.id === 721){
                                opConfigObj.callback(params, function (data) {
                                    if (data > 0) {
                                        layer.open({
                                            title: '提示',
                                            btn: ['前往查看', '继续添加'],
                                            content: '已添加过赔偿单，请确认是否继续添加',
                                            yes: function (index, layero) {
                                                layer.closeAll();
                                                // 跳转工单列表查询
                                                if (params.moduleId == MODULE_ID_ZS) {
                                                    parent.layui.index.openTabsPage(OMS_BASE_URL + "/work/list.action?orderId=" + params.orderId + "&singleWorkType=" + 4, '工单管理');
                                                }else if (params.moduleId == MODULE_ID_YEYX) {
                                                    parent.layui.index.openTabsPage(OMS_BASE_URL + "/ys/work/list.action?orderId=" + params.orderId + "&singleWorkType=" + 4, '工单管理');
                                                }else if (params.moduleId == MODULE_ID_CNHB) {
                                                    parent.layui.index.openTabsPage(OMS_BASE_URL + "/cnhb/work/list.action?orderId=" + params.orderId + "&singleWorkType=" + 4, '工单管理');
                                                }else if (params.moduleId == MODULE_ID_SAAS) {
                                                    parent.layui.index.openTabsPage(OMS_BASE_URL + "/saas/work/list.action?orderId=" + params.orderId + "&singleWorkType=" + 4, '工单管理');
                                                }
                                            },
                                            btn2: function (index, layero) {
                                                layer.close(index);
                                                url = OMS_BASE_URL + '/work/modify/compensate.action';
                                                params.operateId = operateId;
                                                window.currentWork = params;
                                                var operateURL = zmnUtils.serializeURL(url, params);
                                                openDialog({
                                                    title: '赔偿单',
                                                    content: operateURL,
                                                    end: function () {
                                                        window.updateRowDataByWorkId();
                                                    }
                                                });
                                            }
                                        });
                                    } else {
                                        url = OMS_BASE_URL + '/work/modify/compensate.action';
                                        params.operateId = operateId;
                                        window.currentWork = params;
                                        var operateURL = zmnUtils.serializeURL(url, params);
                                        openDialog({
                                            title: '赔偿单',
                                            content: operateURL,
                                            end: function () {
                                                window.updateRowDataByWorkId();
                                            }
                                        });
                                    }
                                });
                            } else if (opConfigObj.id === 4) {
                                opConfigObj.callback(params, function (data) {
                                    // 派单
                                    params.url = OMS_BASE_URL + "/work/modify/distribute.action"
                                    params.operateId = operateId;
                                    jumpToDistributeOrRedistributePage(data, params, opConfigObj)

                                });
                            } else if (opConfigObj.id === 17) {
                                opConfigObj.callback(params, function (data) {
                                    // 派单（新）
                                    params.url = OMS_BASE_URL + "/work/modify/distributeNew.action";
                                    params.operateId = operateId;
                                    jumpToDistributeOrRedistributePage(data, params, opConfigObj)

                                });
                            } else {
                                opConfigObj.callback(params);
                            }
                            return;
                        }
                        switch (opConfigObj.id) {
                            case 502:
                            case 503: {
                                var queryParams = {
                                    workId: params.workId,
                                    orderId: params.orderId
                                };

                                _specialOperateHandlerForComplaintAndAbnormal(opConfigObj, params, function (text) {
                                    var url = zmnUtils.serializeURL(opConfigObj.host + opConfigObj.listURL, queryParams);
                                    parent.layui.index.openTabsPage(url, text);
                                }, function (text) {
                                    var url = zmnUtils.serializeURL(opConfigObj.host + opConfigObj.editURL, queryParams);
                                    parent.layui.index.openTabsPage(url, text);
                                });
                                break;
                            }
                            default:
                                break;
                        }

                        return;
                    }

                    var title = $button.text();

                    if (!url) {
                        layer.msg('操作暂不可用');
                        return;
                    }

                    layer.closeAll();
                    url = OMS_BASE_URL + url;
                    params.operateId = operateId;
                    window.currentWork = params;
                    var operateURL = zmnUtils.serializeURL(url, params);

                    // 呼叫中心逻辑：在 tab 项中打开操作页
                    if (top.isCallCenter) {
                        top.layui.index.openTabsPage(operateURL, '工单操作：' + title);
                        return;
                    }

                    openDialog({
                        title: title,
                        content: operateURL,
                        end: function () {
                            window.updateRowDataByWorkId();
                        }
                    });
                } else {
                    layer.msg(operate.msg)
                }
            });

            // 特殊处理项

        });
    }

    function renderOperationPanel (params, instance) {
        try {
            params['moduleId'] = tableConfig.moduleId;
        }catch (e) {}
        fetchOperationList(params).done(function (data) {
            var htmlStr = createOperationPanelHtml(data);
            var $htmlStr = bindEventForOperateButton(htmlStr, params);

            instance.content($htmlStr);
        });
    }

    function initOperationPanel (externalOptions, getParam) {
        function handleBefore (instance, helper) {
            var $origin = $(helper.origin);
            var params = getParam($origin);

            renderOperationPanel(params, instance);
        }

        function handlePosition (instance, helper, pos) {
            // pos.size =  {
            //     height: 'auto',
            //     width: 430
            // };

            return pos;
        }

        var defaultOption = {
            content: 'Loading...',
            side: 'left',
            theme: 'tooltipster-layui',
            interactive: true,
            contentAsHTML: true,
            animationDuration: '11111111111111',
            maxWidth: 430,
            updateAnimation: 'null',
            functionBefore: handleBefore,
            functionPosition: handlePosition,
        };

        var options = Object.assign({}, defaultOption, externalOptions);

        $('.btn-operate').tooltipster(options);
    }

    exports('list_modify_operation', {
        mapUrl: mapUrl,
        getUrlById: getUrlById,
        getOpConfigById: _getOpConfigById,
        getOpList: fetchOperationList,
        getOpObj: fetchOperationObj,
        initOpPanel: initOperationPanel,
        handler: {
            complaintAndAbnormal: _specialOperateHandlerForComplaintAndAbnormal
        },
        openDialog: openDialog
    });
});
